package com.insight.entity;

import com.insight.common.enums.DatabaseType;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Cache;import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

/**
 * T024: 数据源实体类
 * 存储数据库连接配置信息
 *
 * @author Insight Team
 */
@Entity
@Table(name = "datasource",
        uniqueConstraints = @UniqueConstraint(columnNames = "name"),
        indexes = {
                @Index(name = "idx_datasource_type", columnList = "db_type"),
                @Index(name = "idx_datasource_enabled", columnList = "enabled"),
                @Index(name = "idx_datasource_created_at", columnList = "created_at")
        })
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "datasource")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class DataSource {

    /**
     * 主键ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 数据源名称（唯一）
     */
    @Column(name = "name", nullable = false, unique = true, length = 100)
    private String name;

    /**
     * 数据源描述
     */
    @Column(name = "description", columnDefinition = "TEXT")
    private String description;

    /**
     * 数据库类型
     */
    @Enumerated(EnumType.STRING)
    @Column(name = "db_type", nullable = false, length = 50)
    private DatabaseType dbType;

    /**
     * 数据库主机地址
     */
    @Column(name = "host", nullable = false, length = 255)
    private String host;

    /**
     * 数据库端口
     */
    @Column(name = "port", nullable = false)
    private Integer port;

    /**
     * 数据库名称
     */
    @Column(name = "database_name", nullable = false, length = 100)
    private String databaseName;

    /**
     * 数据库用户名
     */
    @Column(name = "username", nullable = false, length = 100)
    private String username;

    /**
     * 加密后的数据库密码（AES-256）
     */
    @Column(name = "password_encrypted", nullable = false, columnDefinition = "TEXT")
    private String passwordEncrypted;

    /**
     * 明文密码（仅用于测试，不持久化）
     */
    @Transient
    private String password;

    /**
     * 额外连接属性（JSONB格式）
     */
    @Column(name = "connection_properties", columnDefinition = "jsonb")
    @org.hibernate.annotations.JdbcTypeCode(org.hibernate.type.SqlTypes.JSON)
    private String connectionProperties = "{}";

    /**
     * 是否启用
     */
    @Column(name = "enabled", nullable = false)
    private Boolean enabled = true;

    /**
     * 连接池大小
     */
    @Column(name = "connection_pool_size", nullable = false)
    private Integer connectionPoolSize = 10;

    /**
     * 连接超时时间（毫秒）
     */
    @Column(name = "connection_timeout_ms", nullable = false)
    private Integer connectionTimeoutMs = 3000;

    /**
     * 创建时间
     */
    @CreationTimestamp
    @Column(name = "created_at", nullable = false, updatable = false)
    private LocalDateTime createdAt;

    /**
     * 更新时间
     */
    @UpdateTimestamp
    @Column(name = "updated_at", nullable = false)
    private LocalDateTime updatedAt;

    /**
     * 创建人
     */
    @Column(name = "created_by", length = 100)
    private String createdBy;

    /**
     * 更新人
     */
    @Column(name = "updated_by", length = 100)
    private String updatedBy;

    /**
     * 生命周期回调：持久化之前
     */
    @PrePersist
    public void prePersist() {
        if (this.enabled == null) {
            this.enabled = true;
        }
        if (this.connectionPoolSize == null) {
            this.connectionPoolSize = 10;
        }
        if (this.connectionTimeoutMs == null) {
            this.connectionTimeoutMs = 3000;
        }
        if (this.connectionProperties == null) {
            this.connectionProperties = "{}";
        }
    }

    /**
     * 生命周期回调：更新之前
     */
    @PreUpdate
    public void preUpdate() {
        // 可以在这里添加更新前的业务逻辑
    }
}
